#include "global.h"

// Declare the body function as extern so we can link it
extern void processBody();

// Attempts to fork a new process into the ready queue and initalizes
// its stack area. Assigns the new process as a child of running
s16 kfork()
{
	Process* newProcess = dequeue(&freeQueue);
	if (newProcess)
	{
		s16 i;

		// Initialize CPU registers
		for (i = 1; i < 10; ++i)
		{
			newProcess->stack[STACK_SIZE - i] = 0;
		}
		
		// Initialize the new process
		newProcess->stack[STACK_SIZE - 1] = (int)processBody;
		newProcess->stackPointer = &(newProcess->stack[STACK_SIZE - 9]);		
		newProcess->parentProcessID = running->processID;
		newProcess->status = READY;
		newProcess->numChildren = 0;
		enqueue(newProcess, &readyQueue);
		
		// Up the parent child count
		++running->numChildren;
		
		return newProcess->processID;
	}
	return -1;
}
